package com.weixinadmin.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

import com.weixindamin.exception.wxexception;

public class HttpPool {
	 private static Logger logger = Logger.getLogger(HttpPool.class);//log4j
		
	 private static int connectionTimeOut = 70000;
	 private static int socketTimeOut = 60000;
	 private static int maxConnectionPerHost = 5;
	 private static int maxTotalConnections = 40;
	 private static final MultiThreadedHttpConnectionManager managerInstance = new MultiThreadedHttpConnectionManager();
	// 初始化ConnectionManger的方法
	  static
	  {
	   managerInstance.getParams().setConnectionTimeout(connectionTimeOut);
	   managerInstance.getParams().setSoTimeout(socketTimeOut);
	   managerInstance.getParams().setDefaultMaxConnectionsPerHost(
	     maxConnectionPerHost);
	   managerInstance.getParams().setMaxTotalConnections(maxTotalConnections);
	  }	
	 public static MultiThreadedHttpConnectionManager getManager() {
	  return HttpPool.managerInstance;
	 }
	 
	 public String httpget(String url) throws wxexception {
		 return httpget(url,"utf-8");
	 }
	
	 public String httppost(String url,String body) throws wxexception {
		 return httppost(url,body,"utf-8");
	 }
	 //???????????????????wxexception
	 public String httpexe(HttpMethod method , String encode) throws wxexception {
		 HttpClient client = new HttpClient(getManager());
		 //client.executeMethod(method);
		 String result = null;
		 StringBuffer resultBuffer = new StringBuffer();
		 try {
			 	client.executeMethod(method);
			 	BufferedReader in;
			 	if(method instanceof PostMethod) {
				  in = new BufferedReader(new InputStreamReader(method
						     .getResponseBodyAsStream(), ((PostMethod)method).getResponseCharSet()));	 
			   }else{
				  in = new BufferedReader(new InputStreamReader(method
						     .getResponseBodyAsStream(), ((GetMethod)method).getResponseCharSet()));	
			   }
			   
			   String inputLine = null;
			   while ((inputLine = in.readLine()) != null) {
			    resultBuffer.append(inputLine);
			    resultBuffer.append("\n");
			   }
			   in.close();
			   //result = resultBuffer.toString();
			   // iso-8859-1 is the default reading encode
			   if(method instanceof PostMethod) {
				   result = converterStringCode(resultBuffer.toString(),
						   ((PostMethod)method).getResponseCharSet(), encode);
			   }else{
				   result = converterStringCode(resultBuffer.toString(),
						   ((GetMethod)method).getResponseCharSet(), encode);
			   }
			   logger.info(result);
			
		 } catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("http Exception: "+ method.toString());
			e.printStackTrace();			
			//  throw new wxexception();
			  throw new wxexception(wxexception.httperr,"http method: "+method.toString());				
		
		} finally {
			  method.releaseConnection();			 
		}
		  return result;		
	 }
	 
	 public String httppost(String url,String body, String encode) throws wxexception {
		 if(body == null || "".equals(body.trim()))
		 {
			 return null;
		 }
		 PostMethod post = new PostMethod(url);
		 post.setRequestBody(body);
		 
		 return httpexe(post,encode);
	 }
		 
	 public String httpget(String url, String encode) throws wxexception {
		 
		 GetMethod get = new GetMethod(url);
		 
		 return httpexe(get,encode);
	 }
	 
	 public String converterStringCode(String source, String srcEncode,
			   String destEncode) {
			  if (source != null) {
			   try {
			    return new String(source.getBytes(srcEncode), destEncode);
			   } catch (UnsupportedEncodingException e) {
			    e.printStackTrace();
			    return "";
			   }
			  } else {
			   return "";
			  }
	 }
	
	  
}
